<template>
  <el-card>
    <el-form :inline="true" :model="form">
      <el-form-item>
        <el-input
          v-model="form.order_no"
          :placeholder="$t('订单号搜索')"
          clearable
        />
      </el-form-item>
      <!-- <el-form-item>
        <el-select v-model="form.status" :placeholder="$t('订单状态')" clearable class="w-36">
          <el-option :label="$t('进行中')" :value="0" />
          <el-option :label="$t('已完成')" :value="1" />
          <el-option :label="$t('已取消')" :value="2" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-select
          v-model="form.buy_currency"
          :placeholder="$t('买入货币')"
          clearable
          class="w-36"
        >
          <el-option
            v-for="item in currencyList"
            :key="item.key"
            :label="item.name"
            :value="item.symbol"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="form.sell_currency"
          :placeholder="$t('卖出货币')"
          clearable
          class="w-36"
        >
          <el-option
            v-for="item in currencyList"
            :key="item.key"
            :label="item.name"
            :value="item.symbol"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="onSubmit">{{
          $t("查询")
        }}</el-button>
        <el-button type="primary" :icon="Plus" @click="addExchange">{{
          $t("新增换汇")
        }}</el-button>
        <el-button type="info" @click="onExport">{{ $t("导出") }}</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="tableData"
      v-loading="loading"
      :show-summary="showSummary"
      :summary-method="calculateSummary"
    >
      <el-table-column
        prop="merchant_name"
        :label="$t('商户名称')"
        align="center"
      />
      <el-table-column
        prop="order_no"
        :label="$t('订单号')"
        align="center"
        width="260"
      />
      <el-table-column
        :label="$t('换汇卖出金额')"
        align="right"
        prop="sell_amount"
      >
        <template #default="scope">
          {{ numberToCurrencyNo(scope.row.sell_amount) }}
          <el-text>{{ scope.row.sell_currency }}</el-text>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('换汇买入金额')"
        align="right"
        prop="buy_amount"
      >
        <template #default="scope">
          {{ numberToCurrencyNo(scope.row.buy_amount) }}
          <el-text>{{ scope.row.buy_currency }}</el-text>
        </template>
      </el-table-column>
      <el-table-column label="" width="30"></el-table-column>
      <el-table-column :label="$t('汇率')" width="200">
        <template #default="scope">
          <p>
            1 <el-text>{{ scope.row.sell_currency }}</el-text> =
            {{ scope.row.price }}
            <el-text>{{ scope.row.buy_currency }}</el-text>
          </p>
          <p>
            1 <el-text>{{ scope.row.buy_currency }}</el-text> =
            {{ scope.row.o_price }}
            <el-text>{{ scope.row.sell_currency }}</el-text>
          </p>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('订单状态')"
        align="center"
        prop="status_name"
      />
      <el-table-column
        :label="$t('完成时间')"
        :formatter="formatterTime"
        align="center"
        prop="exchange_time"
        width="200"
      >
      </el-table-column>
    </el-table>
    <div class="flex justify-center mt-5">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageable.total"
        :default-page-size="pageable.pageSize"
        :default-current-page="pageable.pageNum"
        :page-sizes="[10, 25, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
  <AddExchange
    :isShowAdd="isShowAdd"
    @closeAddExchange="closeAddExchange"
    @refreshList="refreshList"
    :isChangeShow="true"
  />
</template>
<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { getCurrencyNewApi, orderListNewApi } from "@/api/exchange/index";
import { formatterTime, numberToCurrencyNo, exportExcel } from "@/utils/utils";
import { Search, Plus } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import AddExchange from "./components/addExchange.vue";
const router = useRouter();
const loading = ref(false);
const currencyList = ref([]); //币种
const form = reactive({
  buy_currency: "",
  sell_currency: "",
  order_no: "",
  //   status: "",
});

// 分页
const pageable = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
// 表格数据
const tableData = ref([]);
// 参数
const param = () => {
  return {
    page: pageable.pageNum,
    pagesize: pageable.pageSize,
    buy_currency: form.buy_currency,
    sell_currency: form.sell_currency,
    order_no: form.order_no,
    // status: form.status,
  };
};

const isShowAdd = ref(false);

// 新增换汇
const addExchange = () => {
  isShowAdd.value = true;
};

const onSubmit = () => {
  getTbaleData();
};

const requireSum = ref([]);
const showSummary = ref(false);

// 合计
const calculateSummary = ({ columns, data }) => {
  let sums = [];
  let sumArr = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    let values = null;
    const arr = data.filter((item) => {
      if (requireSum.value.includes(column.property)) {
        return item;
      } else {
        return false;
      }
    });
    if (arr.length > 0) {
      values = null;
      values = arr.map((item) => {
        return Number(item[column.property]);
      });
    }
    if (values) {
      sumArr[index] = `${values.reduce((prev, curr) => {
        return (Number(prev) + Number(curr)).toFixed(2);
      }, 0)}`;
      sums[index] = numberToCurrencyNo(sumArr[index]);
    }
  });
  return sums;
};
// 页码
const handleCurrentChange = (number) => {
  pageable.pageNum = number;
  getTbaleData();
};
// 条数
const handleSizeChange = (number) => {
  pageable.pageSize = number;
  getTbaleData();
};
// 获取币种
const getCurrencyData = async () => {
  const res = await getCurrencyNewApi();
  currencyList.value = res.currency;
};

// 获取表格数据
const getTbaleData = async () => {
  loading.value = true;
  try {
    // 获取数据
    const res = await orderListNewApi(param());
    if (param()?.sell_currency) {
      if (param()?.buy_currency) {
        requireSum.value = ["sell_amount", "buy_amount"];
      } else {
        requireSum.value = ["sell_amount"];
      }
      showSummary.value = true;
    } else if (param()?.buy_currency) {
      if (param()?.sell_currency) {
        requireSum.value = ["buy_amount", "sell_amount"];
      } else {
        requireSum.value = ["buy_amount"];
      }
      showSummary.value = true;
    } else {
      showSummary.value = false;
    }
    loading.value = false;
    tableData.value = res.list;
    pageable.total = res.page.total_count;
  } catch (error) {
    loading.value = false;
  }
};
// 导出
const onExport = async () => {
  const data = Object.assign(param(), { export: 1, pagesize: 9999999 });
  const res = await orderListNewApi(data, "blob");
  exportExcel(res, "exchange_order");
};

const closeAddExchange = () => {
  isShowAdd.value = false;
};

const refreshList = () => {
  isShowAdd.value = false;
  getTbaleData();
};
onMounted(() => {
  Promise.all([getTbaleData(), getCurrencyData()]);
});
</script>
